const url = require('url');

//封装方法改变res，绑定res.send()
function changeRes(res){
    res.send = function(data){
        res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
        res.end(data);
    }
}

//暴露的模块
const Server = function(){
    let G = this;       //全局变量
    this._get = {};
    this._post = {};

    let app = function(req, res){
        changeRes(res);
        //获取路由
        let pathname = url.parse(req.url).pathname;
        if(!pathname.endsWith('/')){
            pathname = pathname + '/';
        }
        //获取请求的方式 get post
        let method = req.method.toLowerCase();
        if(G['_' + method][pathname]){
            if(method == 'post'){
                //执行post请求
                let postStr = '';
                req.on('data', function(chunk){
                    postStr += chunk;
                });
                req.on('end', function(err, chunk){
                    req.body = postStr;/*表示拿到post的值*/
                    G['_' + method][pathname](req, res);
                })
            }
            else{
                G['_' + method][pathname](req, res);
            }
        }
        else{
            res.end('no router');
        }
    }

    app.get = function(str, callback){
        if(! str.endsWith('/')){
            str = str + '/';
        }
        if(!str.startsWith('/')){
            str = '/' + str;
        }
        G._get[str] = callback;
    }

    app.post = function(str, callback){
        if(! str.endsWith('/')){
            str = str + '/';
        }
        if(! str.startsWith('/')){
            str = '/' + str;
        }
        G._post[str] = callback;
    }

    return app;
}

module.exports = Server();